package com.sduept.nwld.dataserver.manager.statistics;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.annotation.PostConstruct;

import javax.inject.Inject;

import com.sduept.core.ParamManager;
import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.sduept.bigdata.fault.entity.FaultRecord;
import com.sduept.bigdata.fault.manager.FaultRecordQueryManager;
import com.sduept.cim.ledger.excetpion.ManagementUnitException;
import com.sduept.cim.ledger.manager.SubstationLedgerManager;
import com.sduept.cim.ledger.model.ManagementUnitDict;
import com.sduept.cim.ledger.model.SubstationLedger;
import com.sduept.cim.ledger.query.services.ManagementUnitQueryService;
import com.sduept.cim.ledger.services.ManagementUnitService;

import com.sduept.core.dao.SuperDAO;
import com.sduept.nwld.dataserver.manager.config.ParamDesc;
import com.sduept.nwld.dataserver.manager.statistics.ProtectKpiCountManager.FaultFastRemoveInner;
import com.sduept.nwld.dataserver.manager.statistics.ProtectKpiCountManager.ProtectCorrectActInner;
import com.sduept.utils.DateUtil;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class StatisticsCommonManager {
	@Autowired
	private ManagementUnitService unitM;
	@Autowired
	private ManagementUnitQueryService unitQ;
	@Autowired
	private SubstationLedgerManager ledgerM;
	@Autowired
	private SuperDAO dao;
	@Autowired
	private FaultRecordQueryManager frqm;

	@Inject
	ParamManager param;

	private Map<String, String> dispatchUnitMap = new HashMap<String, String>();//设备所属调管单位<设备id，调管单位>
	private Map<String, String> maintenanceUnitMap = new HashMap<String, String>();//设备所属检修单位<设备id，检修单位>

	@PostConstruct
	public void init() {
		generateStationUnit();
	}

	/**
	 * 生成变电站管理单位map
	 */
	public void generateStationUnit() {
		List<SubstationLedger> ledgerList = dao.findAll(SubstationLedger.class);
		for(SubstationLedger ledger : ledgerList) {
			dispatchUnitMap.put(ledger.getCimId(), ledger.getDispatchUnit());
			maintenanceUnitMap.put(ledger.getCimId(), ledger.getPrimaryEquipmentScope());//变电站检修单位用变电站管理单位维护中的一次设备检修范围
		}
	}

	/**
	 * 从系统参数中配置
	 */
	public List<Integer> getVoltages() {
		List<Integer> voltages = new ArrayList<Integer>();
		try {
			String voltagestrs = param.get(ParamDesc.VOLTAGE_lEVELS).getValue();
			String[] vs = voltagestrs.split(",");
			for (String v : vs) {
				voltages.add(Integer.valueOf(v));
			}
		} catch (Exception e) {
			log.error("系统参数配置异常，没有配置 voltage_levels，正确配置：pid=nwld_standard_dict,id=voltage_levels,value=220,500");
			voltages.clear();
			voltages.add(220);
			voltages.add(500);
		}
		return voltages;
	}
	/**
	 * 获取一级运维单位（广东电网、广西电网、云南电网、贵州电网、海南电网、深圳电网、超高压、调峰调频等）
	 * @return
	 */
	public List<String> getSubCompanys() {
		List<String> subCompanys = new ArrayList<String>();
		List<ManagementUnitDict> list;
		try {
			list = unitM.getAllMaintenanceScopes();
			for (ManagementUnitDict d : list) {
				subCompanys.add(d.getName());
			}
		} catch (ManagementUnitException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return subCompanys;
	}

	/**
	 * 根据类型获取单位信息，从t_substation_ledger中获取
	 * @param unitType 0：检修单位，1：调管单位
	 * @return
	 */
	public List<String> getUnits(int unitType) {
		List<String> unitsList = new ArrayList<String>();
		if(unitType == 0) {
			String sql = "select primaryEquipmentScope from t_substation_ledger where primaryEquipmentScope is not null "
					+ "and primaryEquipmentScope != '' group by primaryEquipmentScope";
			unitsList = (List<String>) dao.nativeQuery(sql);
		}else {
			String sql = "select dispatchUnit from t_substation_ledger where dispatchUnit is not null and dispatchUnit "
					+ "!= '' group by dispatchUnit";
			unitsList = (List<String>) dao.nativeQuery(sql);
		}
		return unitsList;
	}

	/**
	 * 根据类型获取全部单位信息，从ManagementUnitService接口中获取
	 * @param unitType 0：检修单位，1：调管单位
	 * @return
	 */
	public List<String> getAllUnits(int unitType) {
		List<String> unitsList = new ArrayList<String>();
		if(unitType == 0) {
			try {
				List<ManagementUnitDict> allUnits = unitM.getAllMaintenanceScopes();
				if(allUnits != null) {
					for(ManagementUnitDict unit : allUnits) {
						unitsList.add(unit.getName());
					}
				}
			} catch (ManagementUnitException e) {
				e.printStackTrace();
			}
		}else {
			try {
				List<ManagementUnitDict> allUnits = unitM.getAllDispatchingManagements();
				if(allUnits != null) {
					for(ManagementUnitDict unit : allUnits) {
						unitsList.add(unit.getName());
					}
				}
			} catch (ManagementUnitException e) {
				e.printStackTrace();
			}
		}
		return unitsList;
	}

	// <变电站ID，ledger对象>
	private Map<String, SubstationLedger> getSubstationLedgerMap() {
		Map<String,SubstationLedger> subMap = ledgerM.getSubstationMap();
		return subMap;
	}

	/**
	 * 根据变电站id获取运维单位的父部门，如运维单位为佛山供电局，返回值为广东电网
	 * @param stationId
	 * @return
	 */
	//	private String getFirstLevelByStationId(Map<String, String> deptsRelationMap,Map<String,SubstationLedger> subMap,String stationId) {
	//		if(null == deptsRelationMap) {
	//			deptsRelationMap = unitM.getMaintanceDeptsRelationMap();
	//		}
	//		if(null == subMap) {
	//			subMap = getSubstationLedgerMap();
	//		}
	//		SubstationLedger ledger = subMap.get(stationId);
	//		if(null !=ledger) {
	//			String dept = ledger.getMaintenanceUnit();
	//			String pd = deptsRelationMap.get(dept);
	//			return pd;
	//		} else {
	//			return null;
	//		}
	//	}
	/**
	 * 根据年月获取当月开始时间
	 * @param year
	 * @param month
	 * @return
	 */
	private String getStartDate(Integer year,Integer month) {
		String strDate = "";
		if(null != year) {
			if(null != month) {
				Calendar cal = Calendar.getInstance();
				cal.set(Calendar.YEAR, year);
				cal.set(Calendar.MONTH, month-1);
				//获取某月最小天数
				int firstDay = cal.getMinimum(Calendar.DATE);
				//设置日历中月份的最小天数
				cal.set(Calendar.DAY_OF_MONTH,firstDay);
				//格式化日期
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
				strDate = sdf.format(cal.getTime());
			} else if (null == month) {
				strDate = year+"-01-01 00:00:00";
			}
		}
		return strDate;
	}
	/**
	 * 根据年月获取当月最后时间
	 * @param year
	 * @param month
	 * @return
	 */
	private String getEndDate(Integer year, Integer month) {
		String strDate = "";
		if(null != year) {
			if(null != month) {
				Calendar cal = Calendar.getInstance();
				cal.set(Calendar.YEAR, year);
				cal.set(Calendar.MONTH, month-1);
				//获取某月最大天数
				int lastDay = cal.getActualMaximum(Calendar.DATE);
				//设置日历中月份的最大天数
				cal.set(Calendar.DAY_OF_MONTH, lastDay);
				//格式化日期
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
				strDate = sdf.format(cal.getTime());
			} else if (null == month) {
				strDate = year+"-12-31 23:59:59";
			}
		}
		return strDate;
	}

	public List<?> getListByCondition(Integer year,Integer month,Integer voltage,String sql) {
		String startTime = getStartDate(year, month);
		String endTime = getEndDate(year, month);
		Object[] params = new Object[3];
		params[0] = voltage;
		params[1] = startTime;
		params[2] = endTime;
		List<?> list = dao.nativeQuery(sql, params);
		return list;
	}

	/**
	 * 通过条件查询，返回保护正确动作对象数据
	 * @param year
	 * @param month
	 * @param voltage
	 * @param sql
	 * @return
	 */
	public List<ProtectCorrectActInner> getProtectByConditions(Integer year,Integer month,Integer voltage,String sql) {
		String startTime = getStartDate(year, month);
		String endTime = getEndDate(year, month);
		Object[] params = new Object[3];
		params[0] = voltage;
		params[1] = startTime;
		params[2] = endTime;
		List<ProtectCorrectActInner> list = dao.nativeQuery(ProtectCorrectActInner.class, sql, params);
		return list;
	}

	/**
	 * 通过条件查询，返回故障快速切除对象数据
	 * @param year
	 * @param month
	 * @param voltage
	 * @param sql
	 * @return
	 */
	public List<FaultFastRemoveInner> getRemoveByConditions(Integer year,Integer month,Integer voltage,String sql) {
		String startTime = getStartDate(year, month);
		String endTime = getEndDate(year, month);
		Object[] params = new Object[3];
		params[0] = voltage;
		params[1] = startTime;
		params[2] = endTime;
		List<FaultFastRemoveInner> list = dao.nativeQuery(FaultFastRemoveInner.class, sql, params);
		return list;
	}

	/**
	 * 根据分子公司生成map，其中key为分子公司，value为list中数据
	 * @param list
	 * @param index stationId所在list中的下标
	 * @return
	 */
	public Map<String, List<Object>> getCompanyMap(List<?> list,int index) {
		Map<String,List<Object>> map = new HashMap<String, List<Object>>();
		if(list.size()>0) {
			Object[] arr = (Object[])list.get(0);
			if(index < arr.length) {
				// <变电站ID，ledger对象>
				Map<String,SubstationLedger> subMap = getSubstationLedgerMap();
				// 运维单位Map<子节点,根节点>
				//Map<String, String> deptsRelationMap = unitM.getMaintanceDeptsRelationMap();
				for (Object obj : list) {
					Object[] objs = (Object[])obj;
					String stationId = (String) objs[index];
					//					String company = getFirstLevelByStationId(deptsRelationMap, subMap, stationId);
					ManagementUnitDict company;
					try {
						company = unitQ.getMaintanceScopeByStationId(stationId);
						if(null != company) {
							List<Object> lt = map.get(company.getName());
							if(null == lt) {
								lt = new ArrayList<Object>();
								map.put(company.getName(), lt);
							}
							lt.add(obj);
						}
					} catch (ManagementUnitException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		return map;
	}

	/**
	 *根据所给保护正确动作次数数据 获取调管单位对应的数据map
	 * @param protectList
	 * @return unitMap<调管单位，动作数据列表>
	 */
	public Map<String, List<ProtectCorrectActInner>> getProtectDispatchUnitMap(List<ProtectCorrectActInner> protectList) {
		Map<String, List<ProtectCorrectActInner>> unitMap = new HashMap<String, List<ProtectCorrectActInner>>();
		List<ManagementUnitDict> units;
		try {
			units = unitM.getAllDispatchingManagements();
			units.forEach(u->{
				List<ProtectCorrectActInner> pcaList  = new ArrayList<ProtectCorrectActInner>();
				unitMap.put(u.getName(), pcaList);
			});
			for(ProtectCorrectActInner pca : protectList) {
				String unit = dispatchUnitMap.get(pca.getStationId());//调管单位
				List<ProtectCorrectActInner> pcaList = unitMap.get(unit);
				if(pcaList == null) {
					pcaList = new ArrayList<ProtectCorrectActInner>();
					unitMap.put(unit, pcaList);
				}
				pcaList.add(pca);
			}
		} catch (ManagementUnitException e) {
			e.printStackTrace();
		}

		return unitMap;
	}

	/**
	 * 完善为默认获取所有的检修范围的
	 * 根据所给保护正确动作次数数据获取检修单位对应的数据map
	 * @param protectList
	 * @return unitMap<检修单位，动作数据列表>
	 */
	public Map<String, List<ProtectCorrectActInner>> getProtectMaintenanceUnitMap(List<ProtectCorrectActInner> protectList) {
		Map<String, List<ProtectCorrectActInner>> unitMap = new HashMap<String, List<ProtectCorrectActInner>>();
		try {
			List<ManagementUnitDict> units = unitM.getAllMaintenanceScopes();
			units.forEach(u->{
				List<ProtectCorrectActInner> pcaList  = new ArrayList<ProtectCorrectActInner>();
				unitMap.put(u.getName(), pcaList);
			});
			for(ProtectCorrectActInner pca : protectList) {
				String unit = maintenanceUnitMap.get(pca.getStationId());//检修单位
				List<ProtectCorrectActInner> pcaList = unitMap.get(unit);
				if(pcaList == null) {
					pcaList = new ArrayList<ProtectCorrectActInner>();
					unitMap.put(unit, pcaList);
				}
				pcaList.add(pca);
			}
		} catch (ManagementUnitException e) {
			e.printStackTrace();
		}

		return unitMap;
	}

	/**
	 *根据所给故障快速切除数据 获取调管单位对应的数据map
	 * @param protectList
	 * @return unitMap<调管单位，动作数据列表>
	 */
	public Map<String, List<FaultFastRemoveInner>> getRemoveDispatchUnitMap(List<FaultFastRemoveInner> removeList) {
		Map<String, List<FaultFastRemoveInner>> unitMap = new HashMap<String, List<FaultFastRemoveInner>>();
		List<ManagementUnitDict> units;
		try {
			units = unitM.getAllDispatchingManagements();
			units.forEach(u->{
				List<FaultFastRemoveInner> pcaList  = new ArrayList<>();
				unitMap.put(u.getName(), pcaList);
			});
			for(FaultFastRemoveInner ffr : removeList) {
				String unit = dispatchUnitMap.get(ffr.getStationId());//调管单位
				List<FaultFastRemoveInner> ffrList = unitMap.get(unit);
				if(ffrList == null) {
					ffrList = new ArrayList<FaultFastRemoveInner>();
					unitMap.put(unit, ffrList);
				}
				ffrList.add(ffr);
			}
		} catch (ManagementUnitException e) {
		}

		return unitMap;
	}

	/**
	 * 根据所给故障快速切除数据获取检修单位对应的数据map
	 * @param protectList
	 * @return unitMap<检修单位，动作数据列表>
	 */
	public Map<String, List<FaultFastRemoveInner>> getRemoveMaintenanceUnitMap(List<FaultFastRemoveInner> removeList) {
		Map<String, List<FaultFastRemoveInner>> unitMap = new HashMap<String, List<FaultFastRemoveInner>>();
		List<ManagementUnitDict> units;
		try {
			units = unitM.getAllMaintenanceScopes();
			units.forEach(u->{
				List<FaultFastRemoveInner> pcaList  = new ArrayList<>();
				unitMap.put(u.getName(), pcaList);
			});
			for(FaultFastRemoveInner ffr : removeList) {
				String unit = maintenanceUnitMap.get(ffr.getStationId());//检修单位
				List<FaultFastRemoveInner> ffrList = unitMap.get(unit);
				if(ffrList == null) {
					ffrList = new ArrayList<FaultFastRemoveInner>();
					unitMap.put(unit, ffrList);
				}
				ffrList.add(ffr);
			}
		} catch (ManagementUnitException e) {
		}
		return unitMap;
	}

	/**
	 * list中1必须是“2017-01”，2必须是“500”，3必须是stationId
	 * @param list
	 * @return
	 */
	public Map<String, List<Object>> genMap(List<?> list) {
		//		// <变电站ID，ledger对象>
		//		Map<String,SubstationLedger> subMap = getSubstationLedgerMap();
		//		// 运维单位Map<子节点,根节点>
		//		Map<String, String> deptsRelationMap = unitM.getMaintanceDeptsRelationMap();
		//		Map<String,List<Object>> map = new HashMap<String, List<Object>>();
		//		for (Object object : list) {
		//			Object[] objs = (Object[])object;
		//			String date = objs[0].toString();
		//			String vol = objs[2].toString();
		//			String stationId = objs[1].toString();
		//			String company = getFirstLevelByStationId(deptsRelationMap, subMap, stationId);
		//			if(StringUtils.isNotEmpty(date) && StringUtils.isNotEmpty(vol) && StringUtils.isNotEmpty(company)) {
		//				String key = date+"-"+vol+"-"+company;
		//				List<Object> lt = map.get(key);
		//				if(null == lt) {
		//					lt = new ArrayList<Object>();
		//					map.put(key, lt);
		//				}
		//				lt.add(object);
		//			}
		//		}
		// <变电站ID，ledger对象>
		Map<String,SubstationLedger> subMap = getSubstationLedgerMap();
		// 运维单位Map<子节点,根节点>
		//		Map<String, String> deptsRelationMap = unitM.getMaintanceDeptsRelationMap();
		Map<String,List<Object>> map = new HashMap<String, List<Object>>();
		for (Object object : list) {
			Object[] objs = (Object[])object;
			String date = objs[0].toString();
			String vol = objs[2].toString();
			String stationId = objs[1].toString();
			ManagementUnitDict company;
			try {
				company = unitQ.getMaintanceScopeByStationId(stationId);
				if(StringUtils.isNotEmpty(date) && StringUtils.isNotEmpty(vol) && company != null) {
					String key = date+"-"+vol+"-"+company;
					List<Object> lt = map.get(key);
					if(null == lt) {
						lt = new ArrayList<Object>();
						map.put(key, lt);
					}
					lt.add(object);
				}
			} catch (ManagementUnitException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return map;
	}

	/**
	 *  根据所给保护正确动作次数数据生成检修单位对应的数据map
	 * @param protectList
	 * @return <年-月-调管单位-电压等级，动作数据列表>
	 */
	public Map<String, List<ProtectCorrectActInner>> generateProtectDispatchUnitMap(List<ProtectCorrectActInner> protectList) {
		Map<String, List<ProtectCorrectActInner>> unitMap = new HashMap<String, List<ProtectCorrectActInner>>();//<年-月-调管单位-电压等级，动作数据列表>
		for(ProtectCorrectActInner pca : protectList) {
			String unit = dispatchUnitMap.get(pca.getStationId());//调管单位
			String key = pca.getYear() + "-" + pca.getMonth() + "-" + unit + "-" + pca.getVoltage();
			List<ProtectCorrectActInner> proList = unitMap.get(key);
			if(proList == null) {
				proList = new ArrayList<ProtectCorrectActInner>();
				unitMap.put(unit, proList);
			}
			proList.add(pca);
		}
		return unitMap;
	}

	/**
	 *  根据所给保护正确动作次数数据生成检修单位对应的数据map
	 * @param protectList
	 * @return <年-月-调管单位-电压等级，动作数据列表>
	 */
	public Map<String, List<ProtectCorrectActInner>> generateProtectMaintenanceUnitMap(List<ProtectCorrectActInner> protectList) {
		Map<String, List<ProtectCorrectActInner>> unitMap = new HashMap<String, List<ProtectCorrectActInner>>();//<年-月-调管单位-电压等级，动作数据列表>
		for(ProtectCorrectActInner pca : protectList) {
			String unit = dispatchUnitMap.get(pca.getStationId());//调管单位
			String key = pca.getYear() + "-" + pca.getMonth() + "-" + unit + "-" + pca.getVoltage();
			List<ProtectCorrectActInner> proList = unitMap.get(key);
			if(proList == null) {
				proList = new ArrayList<ProtectCorrectActInner>();
				unitMap.put(unit, proList);
			}
			proList.add(pca);
		}
		return unitMap;
	}

	/**
	 *  根据所给故障快速切除次数数据生成检修单位对应的数据map
	 * @param protectList
	 * @return <年-月-调管单位-电压等级，动作数据列表>
	 */
	public Map<String, List<FaultFastRemoveInner>> generateRemoveDispatchUnitMap(List<FaultFastRemoveInner> removeList) {
		Map<String, List<FaultFastRemoveInner>> unitMap = new HashMap<String, List<FaultFastRemoveInner>>();//<年-月-调管单位-电压等级，动作数据列表>
		for(FaultFastRemoveInner ffr : removeList) {
			String unit = dispatchUnitMap.get(ffr.getStationId());//调管单位
			String key = ffr.getYear() + "-" + ffr.getMonth() + "-" + unit + "-" + ffr.getVoltage();
			List<FaultFastRemoveInner> proList = unitMap.get(key);
			if(proList == null) {
				proList = new ArrayList<FaultFastRemoveInner>();
				unitMap.put(unit, proList);
			}
			proList.add(ffr);
		}
		return unitMap;
	}

	/**
	 *  根据所给故障快速切除次数数据生成检修单位对应的数据map
	 * @param protectList
	 * @return <年-月-调管单位-电压等级，动作数据列表>
	 */
	public Map<String, List<FaultFastRemoveInner>> generateRemoveMaintenanceUnitMap(List<FaultFastRemoveInner> removeList) {
		Map<String, List<FaultFastRemoveInner>> unitMap = new HashMap<String, List<FaultFastRemoveInner>>();//<年-月-调管单位-电压等级，动作数据列表>
		for(FaultFastRemoveInner ffr : removeList) {
			String unit = dispatchUnitMap.get(ffr.getStationId());//调管单位
			String key = ffr.getYear() + "-" + ffr.getMonth() + "-" + unit + "-" + ffr.getVoltage();
			List<FaultFastRemoveInner> proList = unitMap.get(key);
			if(proList == null) {
				proList = new ArrayList<FaultFastRemoveInner>();
				unitMap.put(unit, proList);
			}
			proList.add(ffr);
		}
		return unitMap;
	}


	/***********************以下为统计分析部分封装json数据时用到的可重用的代码************************************/

	/**
	 * 将List<FaultRecord>封装成key为年份的map
	 * @param faultRecords
	 * @return
	 */
	public Map<Integer,List<FaultRecord>> genFaultRecordMapByYear(List<FaultRecord> faultRecords) {
		Map<Integer,List<FaultRecord>> map = new TreeMap<>();
		for (FaultRecord fault : faultRecords) {
			int faultYear = Integer.parseInt(fault.getFaultTime().toString().substring(0, 4));
			List<FaultRecord> lt = map.get(faultYear);
			if(null == lt) {
				lt = new ArrayList<FaultRecord>();
			}
			lt.add(fault);
			map.put(faultYear, lt);
		}
		return map;
	}

	/**
	 * 用空的list补充Map中缺失的年份
	 * @param map
	 */
	public void completeMapByYear(String startYear, String endYear, Map<Integer,List<FaultRecord>> map) {
		int sy = Integer.parseInt(startYear);
		int ey = Integer.parseInt(endYear);
		for(int year = sy; year<=ey; year++) {
			if(!map.containsKey(year)) {
				map.put(year, new ArrayList<FaultRecord>());
			}
		}
	}

	public List<FaultRecord> getFaultRecordsByCondition(String startYear, String endYear, String voltage, String faultType) {
		// 根据起止年、电压等级获取类型为线路的故障
		String sy = startYear+"-01-01 00:00:00";
		String ey = endYear+"-12-31 23:59:59";
		Date start = DateUtil.getDateByString(sy, DateUtil.pattern_ymdhms);
		Date end = DateUtil.getDateByString(ey, DateUtil.pattern_ymdhms);
		Integer vol = null;
		if(!"0".equals(voltage)) {
			vol = Integer.parseInt(voltage);
		}
		List<FaultRecord> faultRecords = frqm.findFaultByTimeEtypeVoltage(start, end, vol, faultType);
		return faultRecords;
	}

	/**
	 * 将List<FaultRecord>转化成按照部门、故障类型统计的JSON数据
	 * @param faultRecords
	 * @return
	 */
	public String genJSONData(List<FaultRecord> faultRecords) {
		Object[] obj = groupFaultListByRankAndType(faultRecords);
		Set<String> types = (Set<String>) obj[0];//故障类型
		StringBuffer buff = new StringBuffer();
		buff.append("[{faultType:[");
		for (String string : types) {
			buff.append("'"+string+"',");
		}
		buff.append("]},");
		Map<String/*单位*/,Map<String/*故障类型*/,List<FaultRecord>>> map = (Map<String, Map<String, List<FaultRecord>>>) obj[1];
		Map<String,List<FaultRecord>> typeMap = null;
		List<FaultRecord> typeList = null;
		for (String dept : map.keySet()) {
			buff.append("{name:'" + dept + "',value:[");
			typeMap = map.get(dept);
			for (String type : types) {
				typeList = typeMap.get(type);
				if(null != typeList) {
					buff.append(typeList.size() + ",");
				} else {
					buff.append("0,");
				}
			}
			buff.append("]},");
		}
		buff.append("]");
		return JSONObject.parse(buff.toString()).toString();
	}

	/**
	 * 为能在一次循环list可以获取所需数据，直接返回Object[]
	 * @param allFaults
	 * @return Object[]
	 * Object[0]:所有的故障类型
	 * Object[1]:Map<String,Map<String,List<FaultRecord>>> map，第一个key为单位，第二个key为故障类型
	 */
	private Object[] groupFaultListByRankAndType(List<FaultRecord> allFaults) {
		Set<String> types = new LinkedHashSet<String>();//故障类型
		//		Map<String,String> deptMap = unitM.getMaintanceDeptsRelationMap();
		Map<String/*单位*/,Map<String/*故障类型*/,List<FaultRecord>>> map = new HashMap<String, Map<String,List<FaultRecord>>>();
		List<ManagementUnitDict> allDepts;
		try {
			allDepts = unitM.getAllMaintenanceScopes();
			for (ManagementUnitDict dept : allDepts) {
				map.put(dept.getName(), new HashMap<String, List<FaultRecord>>());
			}
		} catch (ManagementUnitException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		ManagementUnitDict pdept;
		Map<String,List<FaultRecord>> faultTypeMap = null;
		List<FaultRecord> lt = null;
		for (FaultRecord fault : allFaults) {
			String type = fault.getFaultType();
			if(StringUtils.isEmpty(type)) {
				type = "未知";
			}
			try {
				pdept = unitM.getManagementUnitByName(fault.getRank()==null?"":fault.getRank());
				if(pdept != null) {
					types.add(type);
					faultTypeMap = map.get(pdept.getName());
					if(null == faultTypeMap) {
						continue;
					}
					if(faultTypeMap.isEmpty()) {
						lt = new ArrayList<FaultRecord>();
					} else {
						lt = faultTypeMap.get(type);
						if(null == lt) {
							lt = new ArrayList<FaultRecord>();
						}
					}
					lt.add(fault);
					faultTypeMap.put(type, lt);
				}
			} catch (ManagementUnitException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Object[] obj = {types,map};
		return obj;
	}

}
